import { defineStore } from 'pinia'
import { getLVal, getToken, removeToken, setLVal, setToken } from "@utils/storage.js";
import { getUserPermissionByTokenApi } from "@/api/system/index.js";
import { login, validateLogin } from "@/api/user/index.js";
const modules = import.meta.glob('@/views/**/**.vue')
export const filterAsyncRoutes = (routerList) => {
    //进行递归解析
    //routerList 后端获取的路由
    const res = []

    routerList.forEach(e => {

        let e_new = {
            path: e.path,
            name: e.name,
            meta: {
                title: e.meta.title,
                icon: e.meta.icon,
                appCode: e.meta.appCode,
                componentName: e.meta.componentName,
                internalOrExternal: e.meta.internalOrExternal,
                keepAlive: e.meta.keepAlive,
                layout: (e.layout === null || e.layout === undefined) ? 'home' : e.layout,
            },
            hidden: e.hidden ? e.hidden : undefined,
            component: null

        }

        // 判断iframe

        if (e.menuType === 'M') {
            e_new.component = Layout
        } else {
            e_new.component = modules[`/src/views/${e.component}.vue`]
        }
        // console.log(e_new);
        if (e.children && e.children != null) {
            const children = filterAsyncRoutes(e.children)
            // 保存权限
            e_new = { ...e_new, children: children }
        }

        res.push(e_new)
    })
    return res
}
const useUserStore = defineStore('userStore', {
    state: () => ({
        token: getToken(),
        info: getLVal('info'),
        name: getLVal('name'),
        avatar: getLVal('avatar'),
        routes: [],//全部路由
        addRoutes: [],//后端增加的路由
        init: false,
        useSon: true,
        permissionList: getLVal('permissionList') || [],
        roleCodes: getLVal('roleCodes') || [],
        color: localStorage.getItem(import.meta.env.VITE_COLOR) || "#1890ff"
    }),
    actions: {
        setPermissionList(permissionList) {
            //设置进session中
            setLVal('permissionList', permissionList)
            this.permissionList = permissionList;
        },
        setRoleCodes(roleCodes) {
            //设置进session中
            setLVal('roleCodes', roleCodes)
            this.roleCodes = roleCodes;
        },
        getInfo() {
            return this.info
        },
        setInfo(info) {
            //设置进session中
            setLVal('info', info)
            this.info = info;
        },
        getName() {
            return this.name
        },
        setName(name) {
            //设置进session中
            setLVal('name', name)
            this.name = name;
        },
        getAvatar() {
            return this.avatar
        },
        setAvatar(avatar) {
            //设置进session中
            setLVal('avatar', avatar)
            this.avatar = avatar;
        },
        setColor(color) {
            //设置进session中
            localStorage.setItem(import.meta.env.VITE_COLOR, color)
            this.color = color;
        },
        ValidateLogin(userInfo) {
            return new Promise((resolve, reject) => {
                validateLogin(userInfo).then((response, rej) => {
                    console.log("----cas 登录--------", response);
                    if (response.success) {
                        const result = response.result
                        const userInfo = result.userInfo
                        this.setName({ username: userInfo.username, realname: userInfo.realname })
                        this.setAvatar(userInfo.avatar)
                        this.setInfo(userInfo)
                        this.setRoleCodes(result.roleCodes)
                        setToken(result.token)
                        resolve(response)
                    } else {
                        reject(response)
                    }
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 登录
        Login(userInfo) {
            return new Promise((resolve, reject) => {
                login(userInfo).then((res) => {
                    const result = res.result
                    const userInfo = result.userInfo
                    // sessionStorage.setItem(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
                    this.setName({ username: userInfo.username, realname: userInfo.realname })
                    this.setAvatar(userInfo.avatar)
                    this.setInfo(userInfo)
                    this.setRoleCodes(result.roleCodes)
                    // Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
                    // Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
                    // Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
                    setToken(result.token)
                    // commit('SET_INFO', userInfo)
                    // commit('SET_NAME', { username: userInfo.username,realname: userInfo.realname, welcome: welcome() })
                    // commit('SET_AVATAR', userInfo.avatar)
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 获取路由权限
        GetPermissionList() {
            return new Promise((resolve, reject) => {
                getUserPermissionByTokenApi().then(response => {
                    const menuData = response.result.menu;
                    const authData = response.result.auth;
                    const allAuthData = response.result.allAuth;
                    this.setPermissionList(authData)
                    //Vue.ls.set(USER_AUTH,authData);
                    // sessionStorage.setItem(USER_AUTH,JSON.stringify(authData));
                    // sessionStorage.setItem(SYS_BUTTON_AUTH,JSON.stringify(allAuthData));
                    // if (menuData && menuData.length > 0) {
                    //     // //update--end--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
                    //     commit('SET_PERMISSIONLIST', menuData)
                    //     // 设置系统安全模式
                    //     commit('SET_SYS_SAFE_MODE', response.result.sysSafeMode)
                    // } else {
                    //     reject('getPermissionList: permissions must be a non-null array !')
                    // }
                    resolve(response)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 动态渲染路由
        generateRoutes(routes) {
            // console.log(routes);
            let routerList = JSON.parse(JSON.stringify(routes))
            // console.log(routerList);
            return new Promise((resolve) => {

                const accessedRoutes = filterAsyncRoutes(routerList)
                this.addRoutes = accessedRoutes
                this.routes = routes.concat(accessedRoutes)
                resolve(accessedRoutes)
            })

        }
    }
})

export default useUserStore
